package com.zdp.test.deserialize.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.objenesis.strategy.StdInstantiatorStrategy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @describte:Kyro序列化反序列化
 * @program:ThoughtTest
 * @author:zhengdp
 * @create:2021-12-26 18:39:18
 **/
public class KryoSeDerialize {

    private static final ThreadLocal<Kryo> kryoLocal = ThreadLocal.withInitial(()->{
       Kryo kryo = new Kryo();
       // 自动注册
       kryo.setRegistrationRequired(false);
       return kryo;
    });

    // writexxx 要和 readxxx相对应
    // writeObject 不能和 readClassAndObject对应
    public static byte[] encoder(Object obj) throws IOException {
        // output有缓冲区大小限制，如果对象过大超过缓冲区就会抛出异常
        Output output = new Output(128,100000);
        kryoLocal.get().writeClassAndObject(output,obj);
        output.flush();
        byte[] result = output.toBytes();
        output.close();
        return result;
    }

    public static <T> T decoder(byte[] bytes) throws IOException {
        Input input = new Input(bytes);
        Object obj = kryoLocal.get().readClassAndObject(input);
        return (T)obj;
    }

}
